package com.multi.thread.chapter04.demo11;

import java.util.Calendar;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 *	awaitUntil():当前线程在接到信号、被中断或到达指定最后期限之前一直处于等待状态
 */
public class TestAwaitUntil {
	
	private ReentrantLock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	
	public void waitMethod() {
		try {
			Calendar c = Calendar.getInstance();
			c.add(Calendar.SECOND, 10);
			lock.lock();
			System.out.println("wait begin time : " + System.currentTimeMillis());
			condition.awaitUntil(c.getTime());
			System.out.println("wait   end time : " + System.currentTimeMillis());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public void notifyMethod() {
		try {
			Calendar c = Calendar.getInstance();
			c.add(Calendar.SECOND, 10);
			lock.lock();
			System.out.println("notify begin time : " + System.currentTimeMillis());
			condition.signalAll();
			System.out.println("notify   end tme : " + System.currentTimeMillis());
		} finally {
			lock.unlock();
		}
	}
	
	class ThreadA extends Thread {
		private TestAwaitUntil service = new TestAwaitUntil();

		public ThreadA(TestAwaitUntil service) {
			this.service = service;
		}
		
		@Override
		public void run() {
			service.waitMethod();
		}
	}
	
	class ThreadB extends Thread {
		private TestAwaitUntil service = new TestAwaitUntil();

		public ThreadB(TestAwaitUntil service) {
			this.service = service;
		}
		
		@Override
		public void run() {
			service.notifyMethod();
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final TestAwaitUntil service = new TestAwaitUntil();
		ThreadA a = new TestAwaitUntil().new ThreadA(service);
		a.start();
		Thread.sleep(2000);
		ThreadB b = new TestAwaitUntil().new ThreadB(service);
		b.start();
	}

}
